package org.example.ctsbocc.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpSession;
import org.example.ctsbocc.entity.User;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

@Component("jwtUtil")
public class JwtUtil {

    public String generateToken(User user, LocalDateTime time) {
        assert user != null;

        return Jwts.builder()
                .setSubject(user.getUserId().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000)) // 2小时
                .signWith(SignatureAlgorithm.HS256, time.toString())
                .compact();
    }

    public Boolean validateToken(String token, String key, User user) {
        String subject = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();

        return subject.equals(user.getUserId().toString());
    }

    public String validateToken(String token, LocalDateTime key) {
        return Jwts.parser().setSigningKey(key.toString()).parseClaimsJws(token).getBody().getSubject();
    }
}
